﻿using FineUIPro;
using KPI_SYSTEM.Code;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPI_SYSTEM.ApprovalPage
{
    public partial class ApprovalManagePage : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadBaseData();
                BindData();
            }
            PublicMethod.GetApprovalButton("ApprovalManagePage.aspx", Toolbar2, Grid1);
        }
        /// <summary>
        /// 加载页面必备数据
        /// </summary>
        private void LoadBaseData()
        {
            DataTable tableDept = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,DEPT_NAME FROM DEPT_DICT WHERE PARENT_ID=0 AND DEPT_STATUS=1").Tables[0];
            ddlFormPROCESS_DEPT.DataTextField = "DEPT_NAME";
            ddlFormPROCESS_DEPT.DataValueField = "REC_ID";
            ddlFormPROCESS_DEPT.DataSource = tableDept;
            ddlFormPROCESS_DEPT.DataBind();
            FineUIPro.ListItem processDeptItem = new FineUIPro.ListItem();
            processDeptItem.Value = "-1";
            processDeptItem.Text = "选择部门";
            ddlFormPROCESS_DEPT.Items.Insert(0, processDeptItem);

            DataTable tableMenu = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,MENU_NAME FROM MENU_DICT WHERE PARENT_ID IS NOT NULL AND STATUS=1 ").Tables[0];
            chlFormAPPROVAL_MAPPING.DataTextField = "MENU_NAME";
            chlFormAPPROVAL_MAPPING.DataValueField = "REC_ID";
            chlFormAPPROVAL_MAPPING.DataSource = tableMenu;
            chlFormAPPROVAL_MAPPING.DataBind();


            DataTable tableProcessType = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,DICT_NAME FROM SYSTEM_DICT WHERE PARENT_ID = 
                                                                                      (SELECT TOP 1 REC_ID FROM SYSTEM_DICT WHERE DICT_NAME='审核类别' AND PARENT_ID=0)").Tables[0];
            ddlFormPROCESS_TYPE.DataTextField = "DICT_NAME";
            ddlFormPROCESS_TYPE.DataValueField = "REC_ID";
            ddlFormPROCESS_TYPE.DataSource = tableProcessType;
            ddlFormPROCESS_TYPE.DataBind();

            
        }
        /// <summary>
        /// 加载页面列表数据
        /// </summary>
        private void BindData()
        {
            StringBuilder sqlWhere = new StringBuilder();
            String mainDataSql = @"SELECT A.REC_ID,A.APPROVAL_NAME,A.APPROVAL_MAPPING,A.APPROVAL_REMARK,A.APPROVAL_STATUS,
                                   CASE WHEN A.APPROVAL_STATUS=1 THEN '启用' WHEN A.APPROVAL_STATUS=0 THEN '停用' END AS APPROVAL_STATUS_NAME,
                                   (SELECT STUFF((SELECT ','+ MENU_NAME FROM MENU_DICT  WHERE CHARINDEX(','+CONVERT(VARCHAR,REC_ID)+',',','+A.APPROVAL_MAPPING+',')>0 
                                   FOR XML PATH('')), 1, 1, '')) AS APPROVAL_MAPPING_NAME
                                   FROM HOS_APPROVAL_MAIN AS A WHERE 1=1 {0}";
            if (tbxNameSerach.Text.Trim() != "")
            {
                sqlWhere.Append(" AND A.APPROVAL_NAME LIKE '%" + tbxNameSerach.Text.Trim() + "%'");
            }
            mainDataSql = string.Format(mainDataSql, sqlWhere.ToString());
            DataTable mainDataTable = SqlHelper.ExecuteDataset(CommandType.Text, mainDataSql).Tables[0];
            Grid1.DataSource = mainDataTable;
            Grid1.DataBind();
        }
        /// <summary>
        /// 加载页面列表数据
        /// </summary>
        private void BindProcessData()
        {
            StringBuilder sqlWhere = new StringBuilder();
            String processDataSql = @"SELECT A.REC_ID,A.PROCESS_DEPT,A.PROCESS_TYPE,A.PROCESS_USER,A.PROCESS_REMARK,A.PROCESS_SEQ,
                                   (SELECT DICT_NAME FROM SYSTEM_DICT WHERE REC_ID=A.PROCESS_TYPE) AS PROCESS_TYPE_NAME,
                                   (SELECT DEPT_NAME FROM DEPT_DICT WHERE REC_ID=A.PROCESS_DEPT) AS PROCESS_DEPT_NAME,
                                   (SELECT STUFF((SELECT ','+ USER_NAME FROM USER_DICT WHERE CHARINDEX(','+CONVERT(VARCHAR,REC_ID)+',',','+A.PROCESS_USER+',')>0 
                                   FOR XML PATH('')), 1, 1, '')) AS PROCESS_USER_NAME
                                   FROM HOS_APPROVAL_PROCESS AS A WHERE A.APPROVAL_ID=" + Grid1.SelectedRowID+" ORDER BY A.PROCESS_SEQ";
            processDataSql = string.Format(processDataSql, sqlWhere.ToString());
            DataTable processDataTable = SqlHelper.ExecuteDataset(CommandType.Text, processDataSql).Tables[0];
            GridProcess.DataSource = processDataTable;
            GridProcess.DataBind();
        }
        private void DeleteProcessRowByID(int rowID)
        {
            try
            {
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM HOS_APPROVAL_PROCESS WHERE REC_ID=" + rowID);
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM HOS_APPROVAL_RECORDS WHERE PROCESS_ID=" + rowID);
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM HOS_APPROVAL_RECORDS_BAK WHERE PROCESS_ID=" + rowID);
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败！");
            }
        }
        // 根据行ID来删除行数据
        private void DeleteRowByID(int rowID)
        {
            try
            {
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM HOS_APPROVAL_MAIN WHERE REC_ID=" + rowID);
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败！");
            }
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(Grid1.DataKeys[e.RowIndex][0]);
                try
                {
                    DeleteRowByID(rowID);
                    BindData();
                    ShowNotify("删除数据成功!");

                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }
        protected void Grid1_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            // 如果绑定到 DataTable，那么这里的 DataItem 就是 DataRowView
            DataRowView row = e.DataItem as DataRowView;
            int rowId = Convert.ToInt32(row["REC_ID"]);

            LinkButtonField editField = Grid1.FindColumn("Edit") as LinkButtonField;
            editField.OnClientClick = String.Format("showEditWindow('{0}');", rowId);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<String, String> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs.Clear();
                if (tbxFormAPPROVAL_NAME.Text.Trim() != "")
                {
                    keyValuePairs.Add("APPROVAL_NAME", tbxFormAPPROVAL_NAME.Text.Trim());
                }
                else
                {
                    ShowNotify("流程名称不能为空!");
                    return;
                }
                if (String.Join(",", chlFormAPPROVAL_MAPPING.SelectedValueArray) != "")
                {
                    keyValuePairs.Add("APPROVAL_MAPPING", String.Join(",", chlFormAPPROVAL_MAPPING.SelectedValueArray).TrimEnd(','));
                }
                else
                {
                    ShowNotify("对应模块不能为空!");
                    return;
                }
               
                if (tbxFormAPPROVAL_REMARK.Text.Trim() != "")
                {
                    keyValuePairs.Add("APPROVAL_REMARK", tbxFormAPPROVAL_REMARK.Text.Trim());
                }
                if (ddlFormAPPROVAL_STATUS.SelectedValue != "" && ddlFormAPPROVAL_STATUS.SelectedValue != null)
                {
                    keyValuePairs.Add("APPROVAL_STATUS", ddlFormAPPROVAL_STATUS.SelectedValue);
                }
                String strRowID = hfFormID.Text;
                if (String.IsNullOrEmpty(strRowID))
                {
                    keyValuePairs.Add("CREATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("CREATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM HOS_APPROVAL_MAIN WHERE 1=2", "Add", keyValuePairs);

                    ShowNotify("保存成功!");
                }
                else
                {
                    keyValuePairs.Add("REC_ID", strRowID);
                    keyValuePairs.Add("UPDATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("UPDATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM HOS_APPROVAL_MAIN WHERE REC_ID=" + strRowID, "Update", keyValuePairs);
                    ShowNotify("保存成功!");
                }
                // 重新绑定表格，并点击当前编辑或者新增的行
                BindData();
                PageContext.RegisterStartupScript(String.Format("F('{0}').selectRow('{1}');", Grid1.ClientID, "1") + Window1.GetHideReference());
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }

        }

        protected void ddlFormPROCESS_DEPT_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlFormPROCESS_DEPT.SelectedValue != null && ddlFormPROCESS_DEPT.SelectedValue != "-1")
            {
                DataTable tableProcessUser = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,USER_NAME FROM USER_DICT WHERE USER_DEPT=" + ddlFormPROCESS_DEPT.SelectedValue).Tables[0];
                chlFormPROCESS_USER.DataTextField = "USER_NAME";
                chlFormPROCESS_USER.DataValueField = "REC_ID";
                chlFormPROCESS_USER.DataSource = tableProcessUser;
                chlFormPROCESS_USER.DataBind();
            }
        }

        protected void btnSaveProcess_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<String, String> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs.Clear();
                keyValuePairs.Add("APPROVAL_ID", Grid1.SelectedRowID);
                if (ddlFormPROCESS_DEPT.SelectedValue != "-1" && ddlFormPROCESS_DEPT.SelectedValue != null)
                {
                    keyValuePairs.Add("PROCESS_DEPT", ddlFormPROCESS_DEPT.SelectedValue);
                }
                else
                {
                    ShowNotify("审核部门不能为空!");
                    return;
                }
                if (tbxFormPROCESS_SEQ.Text.Trim() != "")
                {
                    keyValuePairs.Add("PROCESS_SEQ", tbxFormPROCESS_SEQ.Text.Trim());
                }
                else
                {
                    ShowNotify("流程顺序不能为空!");
                    return;
                }
                if (String.Join(",", chlFormPROCESS_USER.SelectedValueArray) != "")
                {
                    keyValuePairs.Add("PROCESS_USER", String.Join(",", chlFormPROCESS_USER.SelectedValueArray).TrimEnd(','));
                }
                else
                {
                    ShowNotify("审核人员不能为空!");
                    return;
                }
                if (ddlFormPROCESS_TYPE.SelectedValue != "-1" && ddlFormPROCESS_TYPE.SelectedValue != null)
                {
                    keyValuePairs.Add("PROCESS_TYPE", ddlFormPROCESS_TYPE.SelectedValue);
                }
                if (tbxFormPROCESS_REMARK.Text.Trim() != "")
                {
                    keyValuePairs.Add("PROCESS_REMARK", tbxFormPROCESS_REMARK.Text.Trim());
                }
                String strRowID = hfFormProcessID.Text;
                if (String.IsNullOrEmpty(strRowID))
                {
                    keyValuePairs.Add("CREATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("CREATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM HOS_APPROVAL_PROCESS WHERE 1=2", "Add", keyValuePairs);

                    ShowNotify("保存成功!");
                }
                else
                {
                    keyValuePairs.Add("REC_ID", strRowID);
                    keyValuePairs.Add("CREATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("CREATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM HOS_APPROVAL_PROCESS WHERE REC_ID=" + strRowID, "Update", keyValuePairs);
                    ShowNotify("保存成功!");
                }
                hfFormID.Text = "";
                tbxFormPROCESS_REMARK.Text = "";
                // 重新绑定表格，并点击当前编辑或者新增的行
                BindProcessData();
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }
        }
        protected void GridProcess_RowClick(object sender, GridRowClickEventArgs e)
        {
            object[] keys = GridProcess.DataKeys[e.RowIndex];
            string rowID = keys[0].ToString();
            hfFormProcessID.Text = rowID;
            DataTable tableProcess = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT * FROM HOS_APPROVAL_PROCESS WHERE REC_ID = " + rowID).Tables[0];
            if (tableProcess.Rows.Count > 0)
            {
                DataTable tableProcessUser = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,USER_NAME FROM USER_DICT WHERE USER_DEPT=" + tableProcess.Rows[0]["PROCESS_DEPT"].ToString()).Tables[0];
                chlFormPROCESS_USER.DataTextField = "USER_NAME";
                chlFormPROCESS_USER.DataValueField = "REC_ID";
                chlFormPROCESS_USER.DataSource = tableProcessUser;
                chlFormPROCESS_USER.DataBind();

                ddlFormPROCESS_DEPT.SelectedValue = tableProcess.Rows[0]["PROCESS_DEPT"].ToString();
                chlFormPROCESS_USER.SelectedValueArray = tableProcess.Rows[0]["PROCESS_USER"].ToString().Split(',');
                tbxFormPROCESS_REMARK.Text = tableProcess.Rows[0]["PROCESS_REMARK"].ToString();
                ddlFormPROCESS_TYPE.SelectedValue = tableProcess.Rows[0]["PROCESS_TYPE"].ToString();
                tbxFormPROCESS_SEQ.Text = tableProcess.Rows[0]["PROCESS_SEQ"].ToString();
            }

        }
        protected void GridProcess_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(GridProcess.DataKeys[e.RowIndex][0]);
                try
                {
                    DeleteProcessRowByID(rowID);
                    BindProcessData();
                    ShowNotify("删除数据成功!");

                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }

        protected void btnEditApprovalProcess_Click(object sender, EventArgs e)
        {
            Window2.GetResetReference();
            BindProcessData();
            PageContext.RegisterStartupScript(String.Format("F('{0}').show();", Window2.ClientID));
        }
    }
}